package com.lms.controller;

import com.lms.bean.User;
import com.lms.service.UserService;
import com.lms.util.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Enumeration;

@Controller
@RequestMapping()//"admin"
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping("tologin")
    public String toLogin(){
        return "/login";
    }

    @RequestMapping("login")
    public String login(String username, String password, HttpSession session, RedirectAttributes redirectAttributes) {
        try {
            if("".equals(username)){
                redirectAttributes.addFlashAttribute("message","请填写用户名");
                return "redirect:/tologin";
            }
            if("".equals(password)){
                redirectAttributes.addFlashAttribute("message","请填写密码");
                return "redirect:/tologin";
            }
            UsernamePasswordToken token = new UsernamePasswordToken(username, MD5Util.code(password));
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);//执行认证
            User user=(User)subject.getPrincipal();
            session.setAttribute("user",user);
            if(user.getRole().getRolename().equals("user")){
                return "forward:/index";
            }else{
                return "forward:/admin/index";
            }

        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message","用户名或密码错误");
            return "redirect:/tologin";
        }
    }
    @RequestMapping("admin/index")
    public String toadminIndex(){
        return "redirect:/request/admin/request-list";
    }

    @RequestMapping("loginOut")
    public String loginOut(HttpSession session){
        Enumeration<String> attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            session.removeAttribute(attributeNames.nextElement());
        }
        return "redirect:/tologin";
    }
}

